<template>
  <div class="email-config">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span>📧 邮件服务状态</span>
          <el-tag v-if="emailStatus.configured" type="success">已配置</el-tag>
          <el-tag v-else type="warning">未配置</el-tag>
        </div>
      </template>

      <!-- 配置说明 -->
      <el-alert
        title="邮件配置说明"
        type="info"
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <template #default>
          <div style="line-height: 1.8;">
            <p style="margin-bottom: 10px;">邮件服务配置在后端配置文件中设置，请联系管理员在 <code>config.py</code> 中配置：</p>
            <ul style="margin: 10px 0; padding-left: 20px;">
              <li><strong>EMAIL_SENDER</strong>: 发件人QQ邮箱</li>
              <li><strong>EMAIL_AUTH_CODE</strong>: QQ邮箱授权码</li>
            </ul>
            <p style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee;">
              <strong>如何获取QQ邮箱授权码：</strong>
            </p>
            <ol style="margin: 10px 0; padding-left: 20px;">
              <li>登录 QQ 邮箱</li>
              <li>进入 <strong>设置 → 账户</strong></li>
              <li>找到 <strong>POP3/IMAP/SMTP服务</strong></li>
              <li>开启 <strong>SMTP服务</strong></li>
              <li>点击 <strong>生成授权码</strong>（需要验证密保）</li>
              <li>复制授权码并配置到后端</li>
            </ol>
          </div>
        </template>
      </el-alert>

      <!-- 当前配置状态 -->
      <el-descriptions :column="2" border v-if="emailStatus.configured">
        <el-descriptions-item label="发件人邮箱">
          {{ emailStatus.sender_email }}
        </el-descriptions-item>
        <el-descriptions-item label="SMTP服务器">
          {{ emailStatus.smtp_server }}:{{ emailStatus.smtp_port }}
        </el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 20px;">
        <el-button type="primary" @click="checkStatus" :loading="statusLoading">
          <el-icon><Refresh /></el-icon>
          刷新状态
        </el-button>
        <el-button type="success" @click="handleTest" :loading="testLoading" :disabled="!emailStatus.configured">
          <el-icon><Promotion /></el-icon>
          发送测试邮件
        </el-button>
      </div>
    </el-card>

    <!-- 发送邮件卡片 -->
    <el-card class="send-card" v-if="emailStatus.configured">
      <template #header>
        <div class="card-header">
          <span>✉️ 发送邮件</span>
        </div>
      </template>

      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="120px">
        <el-form-item label="收件人" prop="to_emails">
          <el-select
            v-model="emailForm.to_emails"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入收件人邮箱，按回车添加"
            style="width: 100%"
          >
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            可以输入多个邮箱地址，按回车键添加
          </div>
        </el-form-item>

        <el-form-item label="邮件主题" prop="subject">
          <el-input 
            v-model="emailForm.subject" 
            placeholder="请输入邮件主题"
            clearable
          />
        </el-form-item>

        <el-form-item label="邮件内容" prop="content">
          <el-input 
            v-model="emailForm.content" 
            type="textarea"
            :rows="6"
            placeholder="请输入邮件内容"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSendEmail" :loading="sendLoading">
            <el-icon><Promotion /></el-icon>
            发送邮件
          </el-button>
          <el-button @click="resetEmailForm">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Message, Promotion, RefreshLeft, Refresh } from '@element-plus/icons-vue'
import { sendEmail, testEmail } from '../api/email.js'
import { API_BASE_URL } from '../api/config.js'
import axios from 'axios'

// 邮件服务状态
const emailStatus = reactive({
  configured: false,
  sender_email: null,
  smtp_server: '',
  smtp_port: 0
})

// 发送邮件表单
const emailFormRef = ref(null)
const emailForm = reactive({
  to_emails: [],
  subject: '',
  content: ''
})

const emailRules = {
  to_emails: [
    { required: true, message: '请输入收件人邮箱', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请输入邮件主题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入邮件内容', trigger: 'blur' }
  ]
}

// 状态
const statusLoading = ref(false)
const testLoading = ref(false)
const sendLoading = ref(false)

// 检查邮件服务状态
const checkStatus = async () => {
  statusLoading.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/api/email/status`)
    
    if (response.data.code === '0') {
      const data = response.data.data
      emailStatus.configured = data.configured
      emailStatus.sender_email = data.sender_email
      emailStatus.smtp_server = data.smtp_server
      emailStatus.smtp_port = data.smtp_port
      
      if (data.configured) {
        ElMessage.success('邮件服务已配置')
      } else {
        ElMessage.warning('邮件服务未配置，请在后端 config.py 中配置')
      }
    }
  } catch (error) {
    console.error('获取邮件服务状态失败:', error)
    ElMessage.error('获取状态失败: ' + (error.message || '未知错误'))
  } finally {
    statusLoading.value = false
  }
}

// 测试邮件
const handleTest = async () => {
  testLoading.value = true
  try {
    const response = await testEmail()
    
    if (response.code === '0') {
      ElMessage.success('测试邮件已发送，请检查收件箱')
    } else {
      ElMessage.error(response.msg || '发送失败')
    }
  } catch (error) {
    console.error('发送测试邮件失败:', error)
    ElMessage.error('发送失败: ' + (error.message || '未知错误'))
  } finally {
    testLoading.value = false
  }
}

// 发送邮件
const handleSendEmail = async () => {
  if (!emailFormRef.value) return
  
  await emailFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    sendLoading.value = true
    try {
      const response = await sendEmail({
        to_emails: emailForm.to_emails,
        subject: emailForm.subject,
        content: emailForm.content,
        content_type: 'plain'
      })
      
      if (response.code === '0') {
        ElMessage.success('邮件发送成功')
        resetEmailForm()
      } else {
        ElMessage.error(response.msg || '发送失败')
      }
    } catch (error) {
      console.error('发送邮件失败:', error)
      ElMessage.error('发送失败: ' + (error.message || '未知错误'))
    } finally {
      sendLoading.value = false
    }
  })
}

// 重置邮件表单
const resetEmailForm = () => {
  emailForm.to_emails = []
  emailForm.subject = ''
  emailForm.content = ''
  if (emailFormRef.value) {
    emailFormRef.value.resetFields()
  }
}

// 页面加载时检查邮件服务状态
onMounted(() => {
  checkStatus()
})
</script>

<style scoped>
.email-config {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.config-card,
.send-card {
  margin-bottom: 20px;
  max-width: 800px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-alert__content) {
  line-height: 1.8;
}
</style>
